/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xtd.facede.retail;

import com.xtd.facade.AbstractFacade;
import com.xtd.model.employment.Employee;
import com.xtd.model.retail.ShootingOrder;
import com.xtd.util.DateTimeUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;

/**
 *
 * @author Lu Yuanbin
 */
@Stateless
public class OrderFacade extends AbstractFacade<ShootingOrder> {

    @EJB
    AccountFacade accountFacade;

    public List<ShootingOrder> find(String searchContent) {
        if (searchContent == null) {
            searchContent = "";
        }
        return getEntityManager().createQuery("select  o from ShootingOrder as o    where o.account.mname like :searchContent or o.account.fname like :searchContent or o.account.mphone like :searchContent or o.account.fphone like :searchContent or o.number like :searchContent   ORDER BY o.createdTime DESC").setParameter("searchContent", "%" + searchContent + "%").getResultList();
    }

    public OrderFacade() {
        super(ShootingOrder.class);
    }

   

    public void update(ShootingOrder order, Employee lastModifiedBy) {
        if (order.getAccount() == null) {
            throw new IllegalArgumentException("未初始化客流量的客户信息");
        } else {
            accountFacade.update(order.getAccount());
        }
        order.setMname(order.getAccount().getMname());
        order.setMphone(order.getAccount().getMphone());
        order.setFname(order.getAccount().getFname());
        order.setFphone(order.getAccount().getFphone());
        order.setMarriageDate(order.getAccount().getMarriageDate());
        order.setLastModifiedBy(lastModifiedBy);
        order.setLastModifiedTime(new Date());

        if (order.getId() == null) {
            order.setNumber(generateNumber("PZ","ShootingOrder"));
            getEntityManager().persist(order);
        } else {
            order = getEntityManager().merge(order);
        }

    }

    public List<ShootingOrder> find(Date startDate, Date endDate) {
        return getEntityManager().createQuery("select  o from ShootingOrder as o  where o.createdTime between :startDate and :endDate order by o.createdTime desc").setParameter("startDate", startDate).setParameter("endDate", endDate).getResultList();
    }

    public List<ShootingOrder> findUnFinishedOrder() {
        return getEntityManager().createQuery("select distinct o from ShootingOrder as o join o.orderCommodityCollection as oc  where o.cancelled is false and oc.cancelled is false and (oc.property = 2 or oc.property = 4)  and oc.quantity > oc.stockout order by o.createdTime desc").getResultList();


    }
}
